package com.laopan.wxpay.bean.sign;

import com.laopan.wxpay.WxConstants;
import com.laopan.wxpay.enums.SignType;
import com.laopan.wxpay.request.WxPayRequest;
import com.laopan.wxpay.utils.NonceCodeUtils;
import com.laopan.wxpay.utils.PemUtils;
import com.laopan.wxpay.utils.SignUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.PrivateKey;

/**
 * 获取与支付签名信息
 *
 * @author laopan
 * @className PrepaySign
 * @date 2021/3/2 16:46
 */
public class PrepaySign {
    private final static Logger log = LoggerFactory.getLogger(WxPayRequest.class);
    /**
     * 预编译id
     */
    private String prepayId;
    /**
     * 商户id
     */
    private String mchId;
    /**
     * appId
     */
    private String appId;
    /**
     * 随机字符串
     */
    private String nonceStr;
    /**
     * 时间戳
     */
    private String timeStamp;
    /**
     * 签名类型
     */
    private String signType;

    public String getPrepayId() {
        return prepayId;
    }

    public void setPrepayId(String prepayId) {
        this.prepayId = prepayId;
    }

    public String getMchId() {
        return mchId;
    }

    public void setMchId(String mchId) {
        this.mchId = mchId;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getNonceStr() {
        return nonceStr;
    }

    public void setNonceStr(String nonceStr) {
        this.nonceStr = nonceStr;
    }

    public String getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

    public String getSignType() {
        return signType;
    }

    public void setSignType(String signType) {
        this.signType = signType;
    }

    public PrepaySign(String mchId, String appId, String prepayId) {
        this.mchId = mchId;
        this.prepayId = prepayId;
        this.appId = appId;
        this.nonceStr = NonceCodeUtils.generateNonceStr();
        this.timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        this.signType = SignType.RSA.getMsg();
    }

    private String getSigData() {
        return this.getAppId() + "\n"
                + this.getTimeStamp() + "\n"
                + this.getNonceStr() + "\n"
                + "prepay_id=" + this.getPrepayId() + "\n";
    }

    public String buildPrepaySign() {
        try {
            String privatePath = PemUtils.getMerPath(mchId, null, WxConstants.PRIVATE_KEY_SUFFIX);
            PrivateKey privateKey = PemUtils.loadPrivateKey(privatePath);
            return SignUtils.signAndEncodeWithBase64(privateKey, getSigData());
        } catch (Exception e) {
            log.error("构建签名异常：", e);
        }
        return null;
    }
}
